package logic

import (
	"context"
	"manage/managerpc/managerpc"
	"manage/models/cache"
	"manage/pkg"
	"strconv"
	"time"

	"manage/api/internal/svc"
	"manage/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LonginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLonginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LonginLogic {
	return &LonginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LonginLogic) Longin(req *types.LonginRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	sms, err := l.svcCtx.ManageRpc.Longin(l.ctx, &managerpc.LonginRequest{
		Account:  req.Account,
		Password: req.Password,
		SendCode: req.SendCode,
	})
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	handler, err := pkg.TokenHandler(strconv.FormatInt(sms.UserId, 10))
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Code:    500,
			Data:    nil,
		}, nil
	}
	ip, _ := pkg.GetLocalIP()
	cache.Rdb.Set(l.ctx, "token"+ip, handler, time.Minute*2)

	return &types.Response{
		Message: "登录成功",
		Code:    200,
		Data:    handler,
	}, nil
}
